package part;

import com.example.dao.StudentDAO;
import com.example.dao.StudentDAOImpl;
import com.example.model.Student;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private StudentDAO studentDAO;

    @Override
    public void init() {
        studentDAO = new StudentDAOImpl(); // 初始化DAO
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String studentId = request.getParameter("studentId");
        String password = request.getParameter("password");

        // 调用DAO验证登录
        Student student = studentDAO.findByStudentIdAndPassword(studentId, password);

        if (student != null) {
            // 登录成功，将学生信息存入Session
            HttpSession session = request.getSession();
            session.setAttribute("student", student);
            response.sendRedirect("students"); // 跳转到学生列表页面
        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("error", "学号或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}